import React, { useState, useEffect, useRef } from'react';
import io from'socket.io-client';
import { useLocation } from'react-router-dom';
import styles from './chat.module.css';
import axios from 'axios';
import Picker from '@emoji-mart/react'
import data from '@emoji-mart/data'
import zh from '@emoji-mart/data/i18n/zh.json';
import './chat.css';  

const socket = io('http://localhost:3000');

const Chat = () => {
  // 从sessionStorage获取userid和username
  const userid = sessionStorage.getItem('userid');
  const username = sessionStorage.getItem('username');
  console.log('userid:', userid);
  console.log('username:', username);

  const location = useLocation();
  const [contacts, setContacts] = useState(
    localStorage.getItem('userlist') 
     ? JSON.parse(localStorage.getItem('userlist')) 
      : []
  );
  const [selectedContact, setSelectedContact] = useState(location.state?.id? location.state.id : null);
  const [chatMessages, setChatMessages] = useState([]);
  const [userId] = useState(userid);
  const [isLoading, setIsLoading] = useState(false);
  const [showEmoji, setShowEmoji] = useState(false);
  const [input, setInput] = useState('');

  // 持久化缓存对象
  const chatCache = useRef({});
  const messageListRef = useRef(null);
  // 新增：控制自动滚动的标志
  const shouldAutoScroll = useRef(true);

  // 安全初始化userId
  useEffect(() => {
    if (!userId) {
      return;
    }
    socket.emit('login', userId);
  }, [userId]);

  // 获取用户列表
  const getlist = async () => {
    try {
      const { data: { contact } } = await axios.get('http://localhost:3000/getContact',{
        params: { _id:userId },

      });
      setContacts(contact);
      console.log('用户列表:', contact);
      
      localStorage.setItem('userlist', JSON.stringify(contact));
    } catch (error) {
      console.error('获取用户列表失败:', error);
    }
  };

  // 监听用户列表变化
  useEffect(() => {
    getlist();
  }, [localStorage.getItem('userlist')]);
  // 滚动事件处理
  useEffect(() => {
    const messageListEl = messageListRef.current;
    if (!messageListEl) return;
    
    const handleScroll = () => {
      // 当用户手动滚动超过距离底部100px时，停止自动滚动
      shouldAutoScroll.current = 
        messageListEl.scrollHeight - messageListEl.scrollTop <= 
        messageListEl.clientHeight + 100;
    };
    
    messageListEl.addEventListener('scroll', handleScroll);
    return () => messageListEl.removeEventListener('scroll', handleScroll);
  }, []);

  // 选择联系人时处理
  useEffect(() => {
    if (!userId ||!selectedContact) return;
    
    const conversationKey = [userId, selectedContact].sort().join('-');
    
    if (chatCache.current[conversationKey]) {
      setChatMessages(chatCache.current[conversationKey]);
      setIsLoading(false);
      requestAnimationFrame(scrollToBottom);
    } else {
      setIsLoading(true);
    }
    
    socket.emit('get_chat_history', { from: userId, to: selectedContact });
  }, [userId, selectedContact]);

  // 处理聊天历史记录
  useEffect(() => {
    socket.on('chat_history', ({ conversationKey, messages }) => {
      chatCache.current[conversationKey] = messages;
      
      if ([userId, selectedContact].sort().join('-') === conversationKey) {
        setChatMessages(messages);
        setIsLoading(false);
        requestAnimationFrame(scrollToBottom);
      }
    });

    return () => socket.off('chat_history');
  }, [userId, selectedContact]);

  // 处理新消息
  useEffect(() => {
    socket.on('private_message', (data) => {
      console.log('收到消息:', data);
      
      const conversationKey = [userId, data.from].sort().join('-');
      
      if (chatCache.current[conversationKey]) {
        chatCache.current[conversationKey] = [...chatCache.current[conversationKey], data];
      }
      
      if (selectedContact === data.from) {
        setChatMessages(prev => [...prev, data]);
        // 确保DOM更新后立即滚动
        requestAnimationFrame(() => {
          if (shouldAutoScroll.current) {
            scrollToBottom();
          }
        });
      }
    });

    return () => socket.off('private_message');
  }, [userId, selectedContact]);

  // 发送文本消息
  const sendMessage = () => {
    if (input && selectedContact) {
      const timestamp = new Date().toISOString();
      const newMessage = {
        from: userId,
        to: selectedContact,
        message: input,
        timestamp
      };
      
      const conversationKey = [userId, selectedContact].sort().join('-');
      chatCache.current[conversationKey] = chatCache.current[conversationKey] 
        ? [...chatCache.current[conversationKey], newMessage] 
        : [newMessage];
      
      setChatMessages(prev => [...prev, newMessage]);
      
      // 发送消息后立即滚动
      requestAnimationFrame(scrollToBottom);
      
      socket.emit('private_message', newMessage);
      setInput('');
    }
  };

  // 优化：强制滚动到底部
  const scrollToBottom = () => {
    const messageListEl = messageListRef.current;
    if (messageListEl) {
      // 直接设置scrollTop为最大高度，确保滚动到底部
      messageListEl.scrollTop = messageListEl.scrollHeight;
      shouldAutoScroll.current = true; // 重置自动滚动标志
    }
  };

  // 初始滚动
  useEffect(() => {
    scrollToBottom();
  }, []);

  
  return (
    <>
      <div className={styles.chatContainer}>
        {/* 联系人列表 */}
        <div className={styles.contactList}>
          <h2>联系人</h2>
          {contacts.map(contact => (
            <div
              key={contact._id}
              className={`${styles.contact} ${selectedContact === contact._id? styles.contactActive : ''}`}
              onClick={() => setSelectedContact(contact._id)}
            >
              <div className={styles.contactAvatar}>{contact.name?.charAt(0).toUpperCase()}</div>
              <span>{contact.name}</span>
            </div>
          ))}
        </div>

        {/* 聊天窗口 */}
        <div className={styles.chatWindow}>
          <div className={styles.chatHeader}>
            <h2>
              {selectedContact 
                ? contacts.find(c => c._id === selectedContact)?.name 
                : '未选择联系人'
              } 
            </h2>
          </div>

          <div className={styles.messageList} ref={messageListRef}>
            {selectedContact? (
              isLoading? (
                <div className={styles.skeletonMessages}>
                  {Array(5).fill(0).map((_, i) => (
                    <div key={i} className={styles.skeletonMessage}>
                      <div className={styles.skeletonAvatar}></div>
                      <div className={styles.skeletonContent}>
                        <div className={styles.skeletonLine}></div>
                        <div className={styles.skeletonLine}></div>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                chatMessages
                  .filter(msg => 
                    msg.from === selectedContact || 
                    (msg.from === userId && msg.to === selectedContact)
                  )
                  .map((msg, index) => (
                    <div 
                      key={index} 
                      className={`${styles.message} ${msg.from === userId? styles.outgoing : styles.incoming}`}
                    >
                      <div className={styles.messageContent}>
                        {msg.message}
                      </div>
                      <div className={styles.messageTime}>
                        {new Date(msg.timestamp).toLocaleTimeString()}
                      </div>
                    </div>
                  ))
              )
            ) : (
              <div className={styles.emptyChat}>
                <div className={styles.emptyChatIcon}>
                  <i className="fas fa-comments"></i>
                </div>
                <p>请选择一个联系人开始聊天</p>
              </div>
            )}
          </div>

          {/* 输入区域 */}
          <div className={styles.inputArea}>
            <button className={styles.iconBtn} onClick={() => setShowEmoji(v => !v)}>😀</button>
            <input
              className={styles.input}
              value={input}
              onChange={e => setInput(e.target.value)}
              placeholder={`请输入消息给 ${selectedContact? contacts.find(c => c._id === selectedContact)?.name : '联系人'}`}
              disabled={!selectedContact}
            />
            <button
              className={styles.sendBtn}
              onClick={sendMessage}
              disabled={!input ||!selectedContact}
            >
              发送
            </button>
            {/* Emoji 选择器 */}
            {showEmoji && (
              <div style={{ position: 'absolute', bottom: 80, left: 120, zIndex: 10 }}>
                <Picker
                  data={data}
                  locale="zh"
                  i18n={zh}
                  onEmojiSelect={emoji => {
                    setInput(input + emoji.native);
                    setShowEmoji(false);
                  }}
                />
              </div>
            )}
          </div>
        </div>
        
      </div>
    </>
  );
};

export default Chat;



